package com.go.where.family.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;

public class HttpClient {

	/**
	 * 默认编码
	 */
	private String DEFAULTENCODE = "UTF-8";

	/**
	 * get方式提交
	 * 
	 * @param url
	 * @param supplyEncode
	 *            供应商返回消息编码方�? * @return
	 * @throws Exception
	 */
	public String doGet(String url, String encode) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				8000);
		HttpGet httpGet = new HttpGet(url);
		httpGet
				.setHeader("User-Agent",
						"Mozilla/5.0 (X11; Linux i686; rv:17.0) Gecko/20100101 Firefox/17.0");
		httpGet.setHeader("X-Requested-With", "XMLHttpRequest");
		HttpResponse httpresponse = httpclient.execute(httpGet);
		try {
			if (httpresponse.getStatusLine().getStatusCode() == 200) {
				InputStream stream = httpresponse.getEntity().getContent();
				HttpEntity httpEntity = httpresponse.getEntity();
				Header header = httpEntity.getContentEncoding();
				if (header != null) {
					encode = header.getName();
				}
				if (encode == null) {
					try {
						Charset cs = Charset.forName(encode);
						encode = cs.name();
					} catch (Exception e) {
					}
				}
				if (encode == null) {
					encode = DEFAULTENCODE;
				}
				StringBuilder sb = new StringBuilder();
				InputStreamReader inReader = new InputStreamReader(stream,
						encode);
				BufferedReader reader = new BufferedReader(inReader);
				String rdline = null;
				String str = null;
				while ((str = reader.readLine()) != null) {
					rdline = str;
					sb.append(rdline).append("\n");
				}

				reader.close();
				return sb.toString().trim();
			} else {
				throw new HttpException("返回信息不正确，返回状�?码："
						+ httpresponse.getStatusLine().getStatusCode());
			}
		} finally {
			httpGet.releaseConnection();
		}
	}

	/**
	 * post提交，pars为提交的参数
	 * 
	 * @param url
	 * @param pars
	 *            响应方响应的页面
	 * @throws Exception
	 */
	public String doPost(String url, Map<String, String> pars) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				8000);
		HttpPost httpPost = new HttpPost(url);
		httpPost
				.setHeader("User-Agent",
						"Mozilla/5.0 (X11; Linux i686; rv:17.0) Gecko/20100101 Firefox/17.0");
		httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
		try {
			List<NameValuePair> nvps = null;
			if (pars != null && !pars.isEmpty()) {
				nvps = new ArrayList<NameValuePair>();
				Iterator<Entry<String, String>> it = pars.entrySet().iterator();
				while (it.hasNext()) {
					Entry<String, String> entry = it.next();
					nvps.add(new BasicNameValuePair(entry.getKey(), entry
							.getValue()));
				}
				UrlEncodedFormEntity encodeform = new UrlEncodedFormEntity(
						nvps, Charset.forName(DEFAULTENCODE));
				httpPost.setEntity(encodeform);
			}
			HttpResponse httpresponse = httpclient.execute(httpPost);
			if (httpresponse.getStatusLine().getStatusCode() == 200) {
				InputStream stream = httpresponse.getEntity().getContent();
				HttpEntity httpEntity = httpresponse.getEntity();
				Header header = httpEntity.getContentEncoding();
				String encode = null;
				if (header != null) {
					encode = header.getName();
				}
				if (encode == null) {
					encode = DEFAULTENCODE;
				}
				StringBuilder sb = new StringBuilder();
				InputStreamReader inReader = new InputStreamReader(stream,
						encode);
				BufferedReader reader = new BufferedReader(inReader);
				String rdline = null;
				while ((rdline = reader.readLine()) != null) {
					sb.append(rdline).append("\n");
				}
				reader.close();
				return sb.toString().trim();
			} else {
				throw new HttpException("返回信息不正确，返回状�?码："
						+ httpresponse.getStatusLine().getStatusCode());
			}
		} finally {
			httpPost.releaseConnection();
		}
	}

	public static void main(String[] args) throws Exception {
		Charset cs = Charset.forName("gb2312");
		System.err.println(cs.name());
	}
}
